package rediscli

import (
	"context"
	"fmt"
	"time"

	"github.com/bsm/redislock"
	"github.com/go-redis/redis/v8"
	"github.com/gogf/gf/frame/g"
)

var Rdb *redis.Client
var Locker *redislock.Client

func init() {

	redisUrl := g.Config().GetString("REDIS_URL")
	fmt.Println("redisUrl", redisUrl)
	opt, err := redis.ParseURL(redisUrl)
	if err != nil {
		panic(err)
	}

	Rdb = redis.NewClient(opt)
	Locker = redislock.New(Rdb)

}

func Lock(key string, fn func() error) {
	ctx := context.Background()
	// Try to obtain lock.
	option := &redislock.Options{RetryStrategy: redislock.ExponentialBackoff(50*time.Millisecond, 5000*time.Millisecond)}
	lock, err := Locker.Obtain(ctx, key, 10*time.Second, option)
	if err == redislock.ErrNotObtained {
		g.Log().Info("Could not obtain lock! key: ", key)
		return

	} else if err != nil {
		g.Log().Error(err)
		return
	}

	// Don't forget to defer Release.
	if lock != nil {
		defer lock.Release(ctx)
	}
	if fn() != nil {
		g.Log().Info("fn error! key! :", key)
	} else {
		g.Log().Info("fn ok! key! :", key)
	}
}

func demo() {
	res := Rdb.Ping(context.Background())
	g.Log().Info("res", res)
}
